<template>
  <div class="crawl-container">
    <div class="form-side">
      <el-form :model="form" label-width="110px" class="crawl-form">
        <el-form-item label="剧集列表链接">
          <el-input v-model="form.drama_list_url" placeholder="请输入剧集列表链接" />
        </el-form-item>
        <el-form-item label="分集列表XPath">
          <el-input v-model="form.episode_list_xpath" placeholder="请输入分集列表XPath" />
        </el-form-item>
        <el-form-item label="剧名">
          <el-input v-model="form.drama_name" placeholder="请输入剧名" />
        </el-form-item>
        <el-form-item label="m3u8文件名">
          <el-input v-model="form.m3u8_filename" placeholder="如 mixed.m3u8 或 index.m3u8" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit" :loading="loading">启动爬虫</el-button>
          <el-button style="margin-left: 8px;" @click="onSearch" :loading="tableLoading">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-side">
      <div style="margin-bottom: 16px; display: flex; align-items: center;">
        <el-button type="primary" @click="onDownload">下载全部分集</el-button>
      </div>
      <el-table :data="tableData" :loading="tableLoading">
        <el-table-column width="200" prop="drama_name" label="剧名" />
        <el-table-column width="120" prop="episode" label="集数" />
        <el-table-column prop="m3u8_url" label="m3u8地址" />
        <el-table-column width="200" prop="created_time" label="创建时间" />
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button
              v-if="row.mp4_url"
              type="primary"
              size="small"
              @click="downloadMp4(row)"
            >下载MP4</el-button>
            <el-button
              v-else
              type="default"
              size="small"
              disabled
            >未生成</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 16px; text-align: right"
        background
        layout="prev, pager, next, jumper, ->, total"
        :total="total"
        :page-size="pageSize"
        :current-page="page"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onUnmounted } from 'vue'
import axios from 'axios'

const form = ref({
  drama_list_url: 'https://v.aik.la/play/1Ee77C-1-1/',
  episode_list_xpath: '/html/body/div[3]/div/div[3]/ul',
  drama_name: '魔道祖师',
  m3u8_filename: 'mixed.m3u8'
})
const loading = ref(false)
const tableLoading = ref(false)
const tableData = ref<any[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)

let timer: any = null

const fetchTableData = async () => {
  tableLoading.value = true
  try {
    if (!form.value.drama_name) {
      tableData.value = []
      total.value = 0
      return
    }
    const res = await axios.get('/api/drama_m3u8_list/', {
      params: {
        drama_name: form.value.drama_name,
        page: page.value,
        page_size: pageSize.value
      }
    })
    // 兼容后端返回的data字段
    tableData.value = res.data.data || res.data.results || []
    total.value = res.data.total
  } finally {
    tableLoading.value = false
  }
}

const startPolling = () => {
  if (timer) clearInterval(timer)
  timer = setInterval(fetchTableData, 5000)
}

const stopPolling = () => {
  if (timer) clearInterval(timer)
  timer = null
}

watch(() => form.value.drama_name, () => {
  page.value = 1
  // stopPolling()  // 注释掉
  tableData.value = []
  total.value = 0
})

const handlePageChange = (val: number) => {
  page.value = val
  fetchTableData()
}

onUnmounted(() => {
  stopPolling()
})

const submit = async () => {
  loading.value = true
  fetchTableData()
  startPolling()
  try {
    await axios.post('/api/crawl/', form.value)
    alert('爬虫任务已提交')
  } finally {
    loading.value = false
  }
}

const onSearch = () => {
  stopPolling()
  fetchTableData()
}

const onDownload = async () => {
  if (!form.value.drama_name) {
    alert('请先输入剧名！')
    return
  }
  try {
    await axios.get('/api/drama_m3u8_download/', {
      params: { drama_name: form.value.drama_name }
    })
    alert('全部分集已下载完成！')
  } catch (e) {
    alert('下载失败！')
  }
}

const downloadMp4 = (row: any) => {
  if (!row.mp4_url) return
  const url = row.mp4_url.startsWith('http') ? row.mp4_url : `${location.origin}${row.mp4_url}`
  const a = document.createElement('a')
  a.href = url
  a.download = `${row.drama_name}_${row.episode}.mp4`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}
</script>

<style scoped>
.crawl-container {
  display: flex;
  flex-direction: row;
  align-items: stretch;
  width: 100%;
  gap: 0;
  min-height: 600px;
}
.form-side {
  width: 300px;
  min-width: 300px;
  max-width: 300px;
  border-right: 1px solid #e0e0e0;
  padding-right: 10px;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}
.table-side {
  flex: 1;
  min-width: 0;
  padding-left: 32px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}
.crawl-form {
  background: #fff;
  padding: 0;
  border-radius: 8px;
  box-shadow: none;
}
</style>